package com.henghe.frame.file.config.in;

import io.minio.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * Description:
 * Author: LiuWenQing
 * Datetime: 2023/4/20 15:03
 */
@Service
public class MinioService {
    @Autowired
    private MinioClient minioClient;

    @Autowired
    private MinioConfig minioConfig;

    /**
     * 占位符
     */
    private static final String BUCKET_PARAM = "${bucket}";

    /**
     * bucket权限-读写
     */
    private static final String READ_WRITE = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":{\"AWS\":[\"*\"]},\"Action\":[\"s3:GetBucketLocation\",\"s3:ListBucket\",\"s3:ListBucketMultipartUploads\"],\"Resource\":[\"arn:aws:s3:::" + BUCKET_PARAM + "\"]},{\"Effect\":\"Allow\",\"Principal\":{\"AWS\":[\"*\"]},\"Action\":[\"s3:DeleteObject\",\"s3:GetObject\",\"s3:ListMultipartUploadParts\",\"s3:PutObject\",\"s3:AbortMultipartUpload\"],\"Resource\":[\"arn:aws:s3:::" + BUCKET_PARAM + "/*\"]}]}";


    /**
     * 创建一个桶
     *
     * @param bucket 桶名称
     * @throws Exception
     */
    public void createBucket(String bucket) throws Exception {
        boolean found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucket).build());
        if (!found) {
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucket).build());
        }
        //设置为只读权限
        minioClient.setBucketPolicy(SetBucketPolicyArgs.builder().bucket(bucket).
                config(READ_WRITE.replace(BUCKET_PARAM, bucket)).build());
    }

    /**
     * 上传升级文件
     *
     * @param inputStream
     * @param fileName
     * @return
     * @throws Exception
     */
    public String uploadFileUpdateApp(InputStream inputStream, String fileName) throws Exception {
        //创建路径
        String photoPath = minioConfig.getUpdateAppFolder() + "/" + dateToStr(nowTimestamp(), "yyyy-MM-dd");
        String importNo = UUID.randomUUID().toString();
        //拼接照片路径和名字
        String fileNewName = photoPath + "/" + importNo + fileName;
        //创建桶
        createBucket(minioConfig.getBucket());
        //将照片插入文件系统
        uploadFile(inputStream, minioConfig.getBucket(), fileNewName);
        //返回路径
        return minioConfig.getEndpoint() + "/" + minioConfig.getBucket() + "/" + fileNewName;
    }

    /**
     * 上传一个文件
     */
    /**
     * 上传一个文件
     *
     * @param inputStream 文件
     * @param bucket      桶名称
     * @param objectName  文件名
     * @throws Exception
     */
    public void uploadFile(InputStream inputStream, String bucket, String objectName) throws Exception {
        //将文件上传到桶里
        minioClient.putObject(PutObjectArgs.builder().bucket(bucket).object(objectName)
                .stream(inputStream, -1, 10485760).build());
    }

    private String dateToStr(Date thisDate, String formatStr) {
        formatStr = (formatStr == null) || (formatStr.trim().length() == 0) ? "yyyy-MM-dd HH:mm:ss" : formatStr;
        SimpleDateFormat formater = new SimpleDateFormat(formatStr);
        return formater.format(thisDate);
    }

    private Timestamp nowTimestamp() {
        return new Timestamp(System.currentTimeMillis());
    }

}
